/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xxx.smartcardio.gui;

import xxx.smartcardio.Tools;
import xxx.smartcardio.engine.TerminalCardMonitor;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.smartcardio.ATR;
import javax.smartcardio.Card;
import javax.smartcardio.CardChannel;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import javax.smartcardio.TerminalFactory;
import javax.swing.JOptionPane;

/**
 * GUI for using the java smartcard API
 * @author Michael
 */
public class SmartCardGui extends javax.swing.JFrame {

    private CardTerminal term = null;
    private Card card = null;
    private CardChannel channel=null;
    private TerminalCardMonitor monitor = null;
    private Runnable cardChange;

    /**
     * Get selected CardTerminal
     * @return 
     */
    public CardTerminal getTerm() {
        return term;
    }

    /**
     * Set selected CardTerminal
     * @param term 
     */
    public synchronized void setTerm(CardTerminal term) {
        if (this.term == term) {
            return;
        }
        if (null != monitor) {
            monitor.dispose();
        }
        setCard(null);
        this.term = term;
        if (term != null) {
            monitor = new TerminalCardMonitor(term);
            monitor.setRunChange(cardChange);
            monitor.start();
        } else {
            monitor = null;
        }
        updateCardPresent();

    }

    /**
     * Get selected Card
     * @return 
     */
    public Card getCard() {
        return card;
    }

    /**
     * Set selected Card
     * @param card 
     */
    private void setCard(Card card) {
        if (this.card == card) {
            return;
        }
        setChannel(null);
        if (null == card) {
            jButtonConnect.setText("Connect");
            jCheckBoxConnected.setSelected(false);
        } else {
            jButtonConnect.setText("Disconnect");
            jCheckBoxConnected.setSelected(true);
        }
        this.card = card;
        updateAtr();
    }
    
    /**
     * Get open CardChannel
     * @return 
     */
    public CardChannel getChannel() {
        return channel;
    }

    /**
     * Set open CardChannel
     * @param channel 
     */
    private void setChannel(CardChannel channel) {
        if (this.channel == channel) {
            return;
        }
        if (null == channel) {
            jButtonOpenCloseChannel.setText("Open Channel");
            jCheckBoxHasChannel.setSelected(false);
        } else {
            jButtonOpenCloseChannel.setText("Close Channel");
            jCheckBoxHasChannel.setSelected(true);
        }
        this.channel = channel;
        updateAtr();
    }

    /**
     * Creates new form SmartCardGui
     */
    public SmartCardGui() {
        this.cardChange = new Runnable() {
            @Override
            public void run() {
                updateCardPresent();
            }
        };
        initComponents();
        initProviders();
    }

    /**
     * Checks if a Provider is provides factories for CardTerminals.
     * Other providers are for cryptography and other purpose.
     * @param p Provider to check
     * @return true if smartcard terminal related provider
     */
    private static boolean isSmartCardProvider(Provider p) {
        for (Service s : p.getServices()) {
            if (s.getType().equals("TerminalFactory")) {
                return true;
            }
        }
        return false;
    }

    /**
     * Add all suitable Providers to selection combobox
     */
    private void initProviders() {
        jComboBoxProviders.removeAllItems();
        for (Provider p : Security.getProviders()) {
            if (isSmartCardProvider(p)) {
                jComboBoxProviders.addItem(p);
            }
        }
    }

    /**
     * Add all "algorithms" for a certain provider to selection combobox
     * @param p 
     */
    private void initAlgos(Provider p) {
        jComboBoxAlgo.removeAllItems();
        if (null == p) {
            return;
        }
        for (Service s : p.getServices()) {
            if (s.getType().equals("TerminalFactory")) {
                jComboBoxAlgo.addItem(s.getAlgorithm());
            }
        }
    }

    /**
     * Add all known CardTerminals for specified provider and
     * algorithm to selection combobox.
     * @param p
     * @param algo 
     */
    private void initTerminals(Provider p, String algo) {
        jComboBoxTerminals.removeAllItems();
        if (null == p || null == algo) {
            return;
        }
        try {
            TerminalFactory f = TerminalFactory.getInstance(algo, null, p);
            for (CardTerminal t : f.terminals().list()) {
                jComboBoxTerminals.addItem(t);
            }
        } catch (NoSuchAlgorithmException | CardException ex) {
            Logger.getLogger(SmartCardGui.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jPanel1 = new javax.swing.JPanel();
        jComboBoxProviders = new javax.swing.JComboBox();
        jComboBoxAlgo = new javax.swing.JComboBox();
        jComboBoxTerminals = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jCheckBoxCardPresent = new javax.swing.JCheckBox();
        jButtonConnect = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldAtr = new javax.swing.JTextField();
        jButtonOpenCloseChannel = new javax.swing.JButton();
        jCheckBoxConnected = new javax.swing.JCheckBox();
        jCheckBoxHasChannel = new javax.swing.JCheckBox();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldApdu = new javax.swing.JTextField();
        jButtonSend = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldResponse = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("SmartCard GUI");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("TerminalFactory Provider / Terminal"));

        jComboBoxProviders.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxProvidersActionPerformed(evt);
            }
        });

        jComboBoxAlgo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxAlgoActionPerformed(evt);
            }
        });

        jComboBoxTerminals.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxTerminalsActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jComboBoxProviders, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jComboBoxAlgo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jComboBoxTerminals, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jComboBoxProviders, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBoxAlgo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBoxTerminals, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        jComboBoxProviders.getAccessibleContext().setAccessibleName("");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Card"));

        jCheckBoxCardPresent.setText("Card Present");
        jCheckBoxCardPresent.setEnabled(false);

        jButtonConnect.setText("Connect");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jCheckBoxCardPresent, org.jdesktop.beansbinding.ELProperty.create("${selected}"), jButtonConnect, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jButtonConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConnectActionPerformed(evt);
            }
        });

        jLabel1.setText("ATR");

        jTextFieldAtr.setEditable(false);

        jButtonOpenCloseChannel.setText("Open Channel");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jCheckBoxConnected, org.jdesktop.beansbinding.ELProperty.create("${selected}"), jButtonOpenCloseChannel, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jButtonOpenCloseChannel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOpenCloseChannelActionPerformed(evt);
            }
        });

        jCheckBoxConnected.setText("Connected");
        jCheckBoxConnected.setEnabled(false);

        jCheckBoxHasChannel.setText("Channel Available");
        jCheckBoxHasChannel.setEnabled(false);

        jLabel2.setText("APDU");

        jButtonSend.setText("Exchange APDU");
        jButtonSend.setToolTipText("");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jCheckBoxHasChannel, org.jdesktop.beansbinding.ELProperty.create("${selected}"), jButtonSend, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jButtonSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSendActionPerformed(evt);
            }
        });

        jLabel3.setText("Response");

        jTextFieldResponse.setEditable(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jCheckBoxCardPresent)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonConnect)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jCheckBoxConnected)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonOpenCloseChannel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCheckBoxHasChannel)
                        .addGap(0, 51, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldAtr))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextFieldApdu))
                            .addComponent(jButtonSend, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextFieldResponse)))))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCheckBoxCardPresent)
                    .addComponent(jButtonConnect)
                    .addComponent(jButtonOpenCloseChannel)
                    .addComponent(jCheckBoxConnected)
                    .addComponent(jCheckBoxHasChannel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldAtr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldApdu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonSend)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldResponse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 8, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /*
     * Combobox and button actions
     */
    
    private void jComboBoxProvidersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxProvidersActionPerformed
        initAlgos((Provider) jComboBoxProviders.getSelectedItem());
    }//GEN-LAST:event_jComboBoxProvidersActionPerformed

    private void jComboBoxAlgoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxAlgoActionPerformed
        initTerminals((Provider) jComboBoxProviders.getSelectedItem(),
                (String) jComboBoxAlgo.getSelectedItem());
    }//GEN-LAST:event_jComboBoxAlgoActionPerformed

    private void jComboBoxTerminalsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTerminalsActionPerformed
        setTerm((CardTerminal) jComboBoxTerminals.getSelectedItem());
    }//GEN-LAST:event_jComboBoxTerminalsActionPerformed

    private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConnectActionPerformed
        connectDisconnectCard();
    }//GEN-LAST:event_jButtonConnectActionPerformed

    private void jButtonOpenCloseChannelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOpenCloseChannelActionPerformed
        openCloseChannel();
    }//GEN-LAST:event_jButtonOpenCloseChannelActionPerformed

    private void jButtonSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSendActionPerformed
        exchangeApdu();
    }//GEN-LAST:event_jButtonSendActionPerformed

    /**
     * GUI main function
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SmartCardGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SmartCardGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SmartCardGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SmartCardGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SmartCardGui().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonConnect;
    private javax.swing.JButton jButtonOpenCloseChannel;
    private javax.swing.JButton jButtonSend;
    private javax.swing.JCheckBox jCheckBoxCardPresent;
    private javax.swing.JCheckBox jCheckBoxConnected;
    private javax.swing.JCheckBox jCheckBoxHasChannel;
    private javax.swing.JComboBox jComboBoxAlgo;
    private javax.swing.JComboBox jComboBoxProviders;
    private javax.swing.JComboBox jComboBoxTerminals;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextFieldApdu;
    private javax.swing.JTextField jTextFieldAtr;
    private javax.swing.JTextField jTextFieldResponse;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    /**
     * Read card present status from GUI element
     * @return 
     */
    public boolean isCardPresent() {
        return jCheckBoxCardPresent.isSelected();
    }

    /**
     * Update card present status in GUI
     */
    private void updateCardPresent() {
        CardTerminal t = getTerm();
        boolean old = isCardPresent();
        boolean newVal;
        if (t == null) {
            newVal = false;
        } else {
            try {
                newVal = t.isCardPresent();
            } catch (CardException ex) {
                Logger.getLogger(SmartCardGui.class.getName()).log(Level.SEVERE, null, ex);
                newVal = false;
            }
        }
        jCheckBoxCardPresent.setSelected(newVal);
        if (!newVal) {
            setCard(null);
        }
        if (old != newVal) {
            firePropertyChange("CardPresent", old, newVal);
        }
    }

    /**
     * Connect to presented card.
     */
    private void connectDisconnectCard() {
        Card c = getCard();
        if (c == null) {
            CardTerminal t = getTerm();
            if (null != t) {
                try {
                    setCard(t.connect("*"));
                } catch (CardException ex) {
                    Logger.getLogger(SmartCardGui.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            try {
                c.disconnect(false);
            } catch (CardException ex) {
                Logger.getLogger(SmartCardGui.class.getName()).log(Level.SEVERE, null, ex);
            }
            setCard(null);
        }
    }

    /**
     * Output ATR from card to GUI element
     */
    private void updateAtr() {
        Card c = getCard();
        if (c == null) {
            jTextFieldAtr.setText("");
        } else {
            ATR atr = c.getATR();
            if (null == atr) {
                jTextFieldAtr.setText("null");
            } else {
                jTextFieldAtr.setText(Tools.hexString(atr.getBytes(), true));
            }
        }
    }
    
    /**
     * Open or close a CardChannel
     */
    private void openCloseChannel() {
        CardChannel c=getChannel();
        if (c == null) {
            Card ca = getCard();
            if (null != ca) {
                setChannel(ca.getBasicChannel());
            }
        } else {
            try {
                if (c.getChannelNumber()!=0) c.close();
            } catch (CardException ex) {
                Logger.getLogger(SmartCardGui.class.getName()).log(Level.SEVERE, null, ex);
            }
            setChannel(null);
        }
    }
    
    /**
     * Read APDU bytes from GUI
     * @return
     * @throws Exception 
     */
    private byte[] getApdu() throws Exception
    {
        byte[] ret=Tools.hexBytes(jTextFieldApdu.getText());
        setApdu(ret);
        return ret;
    }
    
    /**
     * Sets APDU content in GUI
     * @param apdu 
     */
    private void setApdu(byte[] apdu)
    {
        jTextFieldApdu.setText(Tools.hexString(apdu, true));
    }
    
    /**
     * Reads Responsebytes from GUI (not used)
     * @return
     * @throws Exception 
     */
    private byte[] getResponse() throws Exception
    {
        byte[] ret=Tools.hexBytes(jTextFieldResponse.getText());
        setResponse(ret);
        return ret;
    }
    
    /**
     * Write Response bytes to GUI
     * @param apdu 
     */
    private void setResponse(byte[] apdu)
    {
        jTextFieldResponse.setText(Tools.hexString(apdu, true));
    }
    
    /**
     * Exchange APDU with card
     */
    private void exchangeApdu()
    {
        try
        {
            byte[] apdu=getApdu();
            CardChannel c=getChannel();
            CommandAPDU cmd=new CommandAPDU(apdu);
            ResponseAPDU rsp=c.transmit(cmd);
            setResponse(rsp.getBytes());
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex.getLocalizedMessage());
        }
    }
}
